<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
	<title>订单详情</title>
	<meta name="decorator" content="default"/>
	<style type="text/css">
		.table td {
			vertical-align: middle;
		}
		.center{
			text-align: center;
		}
		.footer {
			position:fixed; bottom:0; background:#ABABAB; width:100%; height:35px; line-height:32px; z-index:9999; opacity:1;
			filter:alpha(opacity=60); _bottom:auto; _width:100%; _position:absolute;text-align: right;
			_top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-
			(parseInt(this.currentStyle.marginTop, 10)||0)-(parseInt(this.currentStyle.marginBottom, 10)||0)));
	    }
	</style>
	<script type="text/javascript">
		var dcost = 0;
		var fee = ${fee};//配送费
		var lowFee = ${lowFee};//起送费
		var gift = ${gift};//是否存在新用户礼包
		$(document).ready(function() {
			var nodeLen = $(".jbox-button-panel", top.document).length;
			$(".jbox-button-panel", top.document).eq(nodeLen-1).remove();
			if(${toCreate}){
				parent.mainFrame.location.reload();
				document.location="${ctx}/ivm/order/orderDetail?id=${order.id}";
			}
			$("#inputForm").validate({
				submitHandler: function(form){
					loading('正在提交，请稍等...');
					form.submit();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					error.insertAfter(element);
				}
			});
			
			var totalAmount = 0;
			$("input[name='numbers']").each(function(){
				var number = $(this).val();
				var price = $(this).parent().prev().html();
				totalAmount = accAdd(accMul(price,number),totalAmount);
			});
			if(parseFloat($(".total-amount").html())!=totalAmount){
				dcost = fee;
			}
			calAmount();
		});
		//修改商品数量
		function changeNumber(obj){
			updateNum(obj, 0);
			var price = $(obj).parent().parent().find("input[name='prices']").val();
			var number = $(obj).val();
			$(obj).parent().parent().find("#amounts").html(accMul(price,number));
			$(obj).parent().parent().find("input[name='amounts']").val(accMul(price,number));
			calAmount();
		}
		
		//修改单价
		function changePrice(obj){
			var ff = /^\d+(\.\d+)?$/;
			var val = $(obj).val();
			if(!ff.test(val)){
				alert("请输入整数或小数.");
				$(obj).val("");
			}
			var price = $(obj).val();
			var number = $(obj).parent().parent().find("input[name='numbers']").val();
			$(obj).parent().parent().find("#amounts").html(accMul(price,number));
			$(obj).parent().parent().find("input[name='amounts']").val(accMul(price,number));
			calAmount();
		}
		//修改单价、数量或删除商品时：重新计算总金额
		function calAmount(){
			var totalAmount = 0;
			$("input[name='numbers']").each(function(){
				number = $(this).val();
				price = $(this).parent().parent().find("input[name='prices']").val();
				totalAmount = accAdd(accMul(price,number),totalAmount);
			});
			//存在新用户礼包，则免运费
			if(totalAmount<lowFee && !gift){
				$(".total-amount").html(accAdd(totalAmount,fee));
				$("#amount").val(accAdd(totalAmount,fee));
			}else{
				$(".total-amount").html(totalAmount);
				$("#amount").val(totalAmount);
			}
			if(${order.payType!=1}){
				var orderAmount = $("#orderAmount").val();
				var amount = $("#amount").val();
				$("input[id='deliveryInfo.refund']").val(accSub(orderAmount,amount));
			}
		}
		//重置订单
		function resetDelivery(){
			top.$.jBox.defaults.top="28%";
			top.$.jBox.confirm("是否确认还原订单？",'系统提示',function(v,h,f){
				if(v=='ok'){
					var orderId=$("#orderId").val();
					loading("正在提交，请稍等...");
					document.location="${ctx}/ivm/order/orderDetail?id="+orderId+"&type=1";
				}
			},{buttonsFocus:1});
			top.$('.jbox-body .jbox-icon').css('top','55px');
		}
        //检测商品编号
        function checkProductCode(){
        	if($("#code").val()==""){
				showJBoxMess("请输入商品编号或名称.","error");
				return;
			}
			var obj = $("#code");
			if($(obj).val()!=""){
				//异步保存活动
				$.ajax({
					type: 'post',
					url: '${ctx}/ivm/inventory/checkProductCode',
					data: 'merchantId=${order.merchant.id}&code='+$(obj).val(),
					dataType: 'json',
					success: function(data){
						if(data.status==200){
							var product = data.result;
							var isExists = false;
				        	$("input[id='productCode']").each(function(){
				        		if($(this).val()==product.code){
				        			showJBoxMess("商品"+$(obj).val()+"已存在，请重新输入！","error");
				        			isExists=true;
				        			return false;
				        		}
				        	});
				        	if(isExists) return;
				        	createDeliveryDetail();
						}else{
							showJBoxMess(data.message,"error");
						}
					},
					failure: function(){
						showJBoxMess("操作失败","error");
					}				
				});
			}
		}
		//添加商品
		function createDeliveryDetail(){
			//异步手动生成商品采购清单
			$.ajax({
				type: 'get',
				url: '${ctx}/ivm/order/delivery/productDetail',
				data: 'merchantId=${order.merchant.id}&code='+$("#code").val(),
				dataType: 'json',
				success: function(data){
					if(data.status==200){
						//获取商品最大的排序号
						var maxNum = $("input[name='detailIds']").length;
						$("input[name='sorts']").each(function(obj){
							if($(this).val()-maxNum>0){
								maxNum = $(this).val();
							}
						});
						maxNum = parseInt(maxNum)+1;
						var product = data.result;
						var html = '<tr>';
						html += '<td>';
						html += '<input type="hidden" name="sorts" value="'+maxNum+'"/>';
						html += '<input type="hidden" name="detailIds" value="null"/>';
						html += '<input type="hidden" name="products" value="'+product.id+'"/>';
						html += '<input type="hidden" id="productCode" value="'+product.code+'"/>';
						html += '<input type="hidden" name="amounts" value="0"/>';
						html += '<img id="photo" src="${ctx}/download?filePath='+product.logoUrl+'" style="width:95px; height:67px;" />';
						html += '<td>'+product.code+'</td>';
						html += '<td>'+product.name+'</td>';
						html += '<td>'+product.productUnit.name+'</td>';
						html += '<td><input name="prices" value="'+product.price+'" onchange="changePrice(this)" htmlEscape="false" maxlength="20" class="required" style="text-align: center;width:60px;"/>元</td>';
						html += '<td><input name="numbers" value="0" onchange="changeNumber(this)" htmlEscape="false" maxlength="20" min="1" class="required" style="text-align: center;width:60px;"/>'+product.productUnit.name+'</td>';
						html += '<td><span id="amounts">0</span>元</td>';
						html += '<td><a href="javascript:;" onclick="delProduct(this)">删除</a></td>';
						$(".details").append(html);
						$("#code").val("");
					}else{
						showJBoxMess(data.message,"error");
					}
				},
				failure: function(){
					showJBoxMess("操作失败","error");
				}				
			});
		}
		//删除商品
		function delProduct(obj){
			top.$.jBox.defaults.top="28%";
			top.$.jBox.confirm("确认要删除该商品吗",'系统提示',function(v,h,f){
				if(v=='ok'){
					$(obj).parent().parent().remove();
					calAmount();//重新计算订单总金额
					if($(".details").find("tr").length==0){
						var html = "<tr><td>&nbsp;</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><tr>";
						$(".details").append(html);
					}
				}
			},{buttonsFocus:1});
		}
		//保存type=0：保存，type=1:保存并确认订单
		function saveForm(type){
			var messageInfo = "确认保存吗？";
			if($("input[name='detailIds']").length==0){
				showJBoxMess("对不起，商品列表不能为空，请添加商品！","error");
				return;
			}else{
				top.$.jBox.defaults.top="28%";
				if(type==1){
					messageInfo = "是否保存并确认订单？";
					$("#confirm").val("1");
				}
				top.$.jBox.confirm(messageInfo,'系统提示',function(v,h,f){
					if(v=='ok'){
						$('#inputForm').submit();
					}
				},{buttonsFocus:1});
			}
		}
	</script>
</head>
<body>
<div style="margin:10px 20px 50px 20px;">
	<form:form id="inputForm" modelAttribute="deliveryInfo" action="${ctx}/ivm/order/saveDetail" method="post">
		<form:hidden path="amount"/>
		<input type="hidden" name="deliveryDate" value='<fmt:formatDate value="${deliveryInfo.deliveryDate }" pattern="yyyy-MM-dd HH:mm:ss"/>'/>
		<form:hidden path="deliveryTime"/>
		<form:hidden path="deliveryNo"/>
		<input type="hidden" id="orderAmount" value="${order.amount }"/>
		<input type="hidden" id="orderId" value="${order.id }"/>
		<form:hidden id="confirm" path="order.confirm"/>
		<form:hidden path="order.id"/>
		<form:hidden path="prompt"/>
		<fieldset class="fieldset">
			<legend class="legend">订单信息</legend>
			<div style="width: 375px;float:left">
				订 单 号：${order.orderNo }<br>
				下单时间：<fmt:formatDate value="${order.createDate }" pattern="yyyy-MM-dd HH:mm:ss"/><br>
				付款时间：<fmt:formatDate value="${order.payDate}" pattern="yyyy-MM-dd HH:mm:ss"/><br>
				下 单 人：${order.user.name }<br>
				备　　注：<input name="remarks" value="${order.remarks }" htmlEscape="false" maxlength="100" style="padding: 0px; margin:0px;border: 0px;width: 520px;position: absolute;"/>
			</div>
			<div>
				要求收货时间：<input name="timeText" value="${deliveryInfo.timeText }" htmlEscape="false" maxlength="20" class="required" style="padding: 0px; margin:0px;border: 0px;width: 120px;"/><br>
				实际送达时间：<fmt:formatDate value="${order.deliveryIndent.deliveryDate }" pattern="yyyy-MM-dd HH:mm:ss"/><br>
				订单总金额：<span class="total-amount">${deliveryInfo.amount }</span>元<br>
				下单人电话：${order.user.mobile }<br>
				<c:if test="${order.orderDiscount != null}"><br>折扣后总金额：${order.disAmount }元</c:if>
			</div>
		</fieldset>
		<fieldset class="fieldset">
			<legend class="legend">收货信息</legend>
			<div>
				姓　　名：<input name="name" value="${deliveryInfo.name }" htmlEscape="false" maxlength="20" class="required" style="padding: 0px; margin:0px;border: 0px;width: 120px;"/><br>
				电　　话：<input name="phone" value="${deliveryInfo.phone }" htmlEscape="false" maxlength="20" class="required" style="padding: 0px; margin:0px;border: 0px;width: 120px;"/><br>
				收货地址：<input name="address" value="${deliveryInfo.address }" htmlEscape="false" maxlength="100" class="required" style="padding: 0px; margin:0px;border: 0px;width: 520px;"/>
			</div>
		</fieldset>
		<form:hidden path="id"/>
		<tags:message content="${message}"/>
		<form:hidden id="deliveryInfo.refund" path="refund" />
		<!-- 收货人信息 -->
		<table id="contentTable" class="table table-striped table-bordered table-condensed">
			<thead>
				<tr>
					<th width="95">商品封面</th>
					<th>编号</th>
					<th>名称</th>
					<th>单位</th>
					<th>单价</th>
					<th>数量</th>
					<th>金额</th>
					<th>操作</th>
				</tr>
			</thead>
			<tbody class="details">
			<c:forEach items="${orderList}" var="detail">
				<tr>
					<td>
						<input type="hidden" name="sorts" value="${detail.sort }"/>
						<input type="hidden" name="detailIds" value="${detail.id }"/>
						<input type="hidden" name="products" value="${detail.product.id }"/>
						<input type="hidden" id="productCode" value="${detail.product.code }"/>
						<input type="hidden" name="amounts" value="${detail.amount }"/>
						<img id="photo" src="${ctx}/download?filePath=${detail.product.logoUrl }" style="width:95px; height:67px;" />
					</td>
					<td>${detail.product.code}</td>
					<td>${detail.product.name}</td>
					<td>${detail.product.productUnit.name}</td>
					<td>
						<input name="prices" value="${detail.price }" onchange="changePrice(this)" htmlEscape="false" maxlength="20" class="required" style="text-align: center;width:60px;"/>元
					</td>
					<td>
						<input name="numbers" value="${detail.number }" onchange="changeNumber(this)" htmlEscape="false" maxlength="20" min="1" class="required" style="text-align: center;width:60px;"/>
						${detail.product.productUnit.name}
					</td>
					<td><span id="amounts">${detail.amount}</span>元</td>
					<td><a href="javascript:;" onclick="delProduct(this)">删除</a></td>
				</tr>
			</c:forEach>
			</tbody>
		</table>
	</form:form>
</div>
<!--endprint-->
<c:if test="${(order.payType != '1' && order.payStatus == '1') || order.payType == '1'}">
	<div class="footer">
		<input type="text" id="code" name="code" htmlEscape="false" maxlength="200" class="input-small" style="margin-bottom: 0px; width: 180px;" placeholder="请输入商品编号或商品名称"/>
		<input class="btn btn-primary" type="button" onclick="checkProductCode()" value="添加商品"/>
		<input id="btnSubmit" class="btn btn-primary" type="button" value="保存" onclick="saveForm(0)"/>
		<c:if test="${order.confirm=='0'}">
			<input id="btnSubmit" class="btn btn-primary" type="button" value="保存并确认订单" onclick="saveForm(1)"/>
		</c:if>
		<input type="button" class="btn btn-primary" onclick="resetDelivery()" value="一键还原"/>
	</div>
</c:if>
</body>
</html>